<%_
// 本表是否有配置 字典数据 的字段
const _hasDict = fieldList.some((fieldItem) => fieldItem.dict != '')
// 本表 配置的字典标识数组（去重过的）
const _uniDictList = [...new Set(fieldList.filter((fieldItem) => fieldItem.dict != '').map((item) => item.dict))]
// 本表是否有配置 搜索 的字段
const _hasQuery = fieldList.some((fieldItem) => fieldItem.query != '')
// 主键字段数据
const pkField =  fieldList.find((item) => item.key === 'PRI') || {}
_%>
<template>
  <div class="app-container">
    <%_ if (_hasQuery) { _%>
    <!-- 查询条件 -->
    <el-form ref="queryFormRef" :model="queryParams" v-show="showSearch" label-width="auto" :inline="true" @submit.prevent>
      <%_ for (const field of fieldList) { _%>
      <%_ if (field.query) { _%>
      <%_ // 已配置查询 _%>
      <%_ if (field.display === 'input') { _%>
      <%_ // 文本框 _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-input v-model="queryParams.<%= field.name %>" placeholder="<%= field.label %>" clearable @keyup.enter="handleQuery" style="width: 214px"></el-input>
      </el-form-item>
      <%_ } else if (field.display === 'inputNumber') { _%>
      <%_ // 数字框 _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-input v-model="queryParams.<%= field.name %>" placeholder="<%= field.label %>" clearable @keyup.enter="handleQuery" style="width: 214px" type="number"></el-input>
      </el-form-item>
      <%_ } else if (field.display === 'textarea') { _%>
      <%_ // 文本域 _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-input v-model="queryParams.<%= field.name %>" placeholder="<%= field.label %>" @keyup.enter="handleQuery" type="textarea"></el-input>
      </el-form-item>
      <%_ } else if (field.display === 'select') { _%>
      <%_ // 下拉框 _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-select v-model="queryParams.<%= field.name %>" placeholder="<%= field.label %>" clearable>
          <%_ if (field.dict) { _%>
          <el-option v-for="dict in <%= field.dict %>" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          <%_ } else { _%>
          <el-option label="选择字典生成或手动编写数据" value="1"></el-option>
          <%_ } _%>
        </el-select>
      </el-form-item>
      <%_ } else if (field.display === 'radio') { _%>
      <%_ // 单选框 _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-radio-group v-model="queryParams.<%= field.name %>">
          <%_ if (field.dict) { _%>
          <el-radio v-for="dict in <%= field.dict %>" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          <%_ } else { _%>
          <el-radio label="1">选择字典生成或手动编写数据</el-radio>
          <%_ } _%>
        </el-radio-group>
      </el-form-item>
      <%_ } else if (field.display === 'checkbox') { _%>
      <%_ // 复选框 _%>
      <%_ } else if (field.display === 'date' && field.query !== 'BETWEEN') { _%>
      <%_ // 日期（非范围） _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-date-picker v-model="queryParams.<%= field.name %>" type="date" value-format="YYYY-MM-DD" placeholder="请选择<%= field.label %>" clearable></el-date-picker>
      </el-form-item>
      <%_ } else if (field.display === 'date' && field.query === 'BETWEEN') { _%>
      <%_ // 日期（范围） _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-date-picker v-model="queryParams.<%= field.name %>" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" clearable></el-date-picker>
      </el-form-item>
      <%_ } else if (field.display === 'datetime' && field.query !== 'BETWEEN') { _%>
      <%_ // 日期时间（非范围） _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-date-picker v-model="queryParams.<%= field.name %>" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择<%= field.label %>" clearable></el-date-picker>
      </el-form-item>
      <%_ } else if (field.display === 'datetime' && field.query === 'BETWEEN') { _%>
      <%_ // 日期时间（范围） _%>
      <el-form-item label="<%= field.label %>" prop="<%= field.name %>">
        <el-date-picker v-model="queryParams.<%= field.name %>" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" clearable></el-date-picker>
      </el-form-item>
      <%_ } else if (field.display === 'imageUpload') { _%>
      <%_ // 图片上传 _%>
      <%_ } else if (field.display === 'fileUpload') { _%>
      <%_ // 文件上传 _%>
      <%_ } else if (field.display === 'editor') { _%>
      <%_ // 富文本 _%>
      <%_ } else { %>
      <%_ // 其他 _%>
      <%_ } _%>
      <%_ } _%>
      <%_ } _%>
      <el-form-item>
        <el-button type="primary" @click="handleQuery" v-autoBlur>搜索</el-button>
        <el-button @click="resetQuery" v-autoBlur>重置</el-button>
      </el-form-item>
    </el-form>
    <%_ } _%>
    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <%_ if (hasAdd) { _%>
      <el-col :span="1.5" v-hasPermit="['<%= addPermisstion %>']">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-autoBlur>新增</el-button>
      </el-col>
      <%_ } _%>
      <%_ if (hasDel) { _%>
      <el-col :span="1.5" v-hasPermit="['<%= delPermisstion %>']">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-autoBlur>删除</el-button>
      </el-col>
      <%_ } _%>
      <%_ if (hasExport) { _%>
      <el-col :span="1.5" v-hasPermit="['<%= exportPermisstion %>']">
        <el-button type="success" plain icon="Download" @click="handleExport" :loading="btnExportLoading" v-autoBlur>导出</el-button>
      </el-col>
      <%_ } _%>
      <right-toolbar :search="<%= _hasQuery %>"<% if(_hasQuery) { %> v-model:showSearch="showSearch"<% } %> @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格 -->
    <el-table :data="tableData" empty-text="暂无数据~"<% if (hasDel || hasExport) { %> @selection-change="handleSelectionChange"<% } %> v-loading="loading">
      <%_ if (hasDel || hasExport) { _%>
      <el-table-column type="selection" width="55" align="center" />
      <%_ } _%>
      <%_ for (const field of fieldList) { _%>
      <%_ // 单位处理 _%>
      <%_ const label = field.unit ? `${field.label}（${field.unit}）` : field.label _%>
      <%_ if (field.list) { _%>
      <%_ // 已配置列表显示 _%>
      <%_ if (field.display === 'input') { _%>
      <%_ // 文本框 _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>"></el-table-column>
      <%_ } else if (field.display === 'inputNumber') { _%>
      <%_ // 数字框 _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>"></el-table-column>
      <%_ } else if (field.display === 'textarea') { _%>
      <%_ // 文本域 _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>"></el-table-column>
      <%_ } else if (field.display === 'select') { _%>
      <%_ // 下拉框 _%>
      <%_ if (field.dict) { _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>">
        <template #default="{ row }">
          <dict-tag :options="<%= field.dict %>" :value="row.<%= field.name %>" />
        </template>
      </el-table-column>
      <%_ } else { _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>"></el-table-column>
      <%_ } _%>
      <%_ } else if (field.display === 'radio') { _%>
      <%_ // 单选框 _%>
      <%_ if (field.dict) { _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>">
        <template #default="{ row }">
          <dict-tag :options="<%= field.dict %>" :value="row.<%= field.name %>" />
        </template>
      </el-table-column>
      <%_ } else { _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>"></el-table-column>
      <%_ } _%>
      <%_ } else if (field.display === 'checkbox') { _%>
      <%_ // 复选框 _%>
      <%_ if (field.dict) { _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>">
        <template #default="{ row }">
          <dict-tag :options="<%= field.dict %>" :value="row.<%= field.name %> ? row.<%= field.name %>.split(',') : []" />
        </template>
      </el-table-column>
      <%_ } else { _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>"></el-table-column>
      <%_ } _%>
      <%_ } else if (field.display === 'date') { _%>
      <%_ // 日期 _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>" width="180"></el-table-column>
      <%_ } else if (field.display === 'datetime') { _%>
      <%_ // 日期时间 _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>" width="180"></el-table-column>
      <%_ } else if (field.display === 'imageUpload') { _%>
      <%_ // 图片上传 _%>
      <el-table-column label="<%= label %>" align="center" prop="<%= field.name %>">
        <template #default="{ row }">
          <image-preview :src="row.<%= field.name %>" :width="50" :height="50" />
        </template>
      </el-table-column>
      <%_ } else if (field.display === 'fileUpload') { _%>
      <%_ // 文件上传 不显示 _%>
      <%_ } else if (field.display === 'editor') { _%>
      <%_ // 富文本 不显示 _%>
      <%_ } else { %>
      <%_ // 其他 不显示 _%>
      <%_ } _%>
      <%_ } _%>
      <%_ } _%>
      <%_ // 是否有 编辑 删除 功能 _%>
      <%_ if (hasEdit || hasDel) { _%>
      <el-table-column label="操作" align="center" fixed="right" width="236" v-hasPermit="['<%= editPermisstion %>', '<%= delPermisstion %>']">
        <template #default="{ row }">
          <%_ if (hasEdit) { _%>
          <el-button link type="primary" @click="handleEdit(row)" v-hasPermit="['<%= editPermisstion %>']" v-autoBlur>修改</el-button>
          <%_ } _%>
          <%_ if (hasDel) { _%>
          <el-button link type="danger" @click="handleDelete(row)" v-hasPermit="['<%= delPermisstion %>']" v-autoBlur>删除</el-button>
          <%_ } _%>
        </template>
      </el-table-column>
      <%_ } _%>
    </el-table>
    <!-- 分页 -->
    <pagination v-if="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.limit" @pagination="getList"></pagination>
    <%_ if (hasAdd || hasEdit) { _%>
    <!-- 添加 & 编辑 对话框 -->
    <AddOrEdit ref="addOrEditRef" @updateList="getList"></AddOrEdit>
    <%_ } _%>
  </div>
</template>

<script setup name="<%= fn.snakeFormatHump(name, true) %>">
import { ref, getCurrentInstance, provide, watch } from 'vue'
import { cloneDeep } from 'lodash-es'
<%_ if (_hasDict) { _%>
import { labelValueToKeyValue } from '@/utils/roc'
<%_ } _%>
<%_ if (hasExport) { _%>
import { exportJsonToExcel, exportFormatJson } from '@/utils/excel'
<%_ } _%>
import { list<%= fn.snakeFormatHump(name, true) %><% if (hasDel) { %>, del<%= fn.snakeFormatHump(name, true) %><% } %><% if (hasExport) { %>, export<%= fn.snakeFormatHump(name, true) %><% } %> } from '@/api/<%= fn.snakeFormatHump(name) %>'
<%_ if (hasAdd || hasEdit) { _%>
import AddOrEdit from './addOrEdit.vue'
<%_ } _%>

const { proxy } = getCurrentInstance()
<%_
// 字典 js变量 js方法参数 处理
let dictsDot = "";
let dictsArgs = "";
for (let i = 0; i < _uniDictList.length; i++) {
  const dict = _uniDictList[i]
  if (i != _uniDictList.length - 1){
    dictsDot += dict + ", ";
    dictsArgs += "'" + dict + "'" + ", ";
  } else {
    dictsDot += dict;
    dictsArgs += "'" + dict + "'";
  }
}
_%>
<%_ if (_hasDict) { _%>
const { <%- dictsDot %> } = proxy.useDict(<%- dictsArgs %>)
// 注入字典数据
<%_ for (const dict of _uniDictList) { _%>
provide('<%= dict %>', <%= dict %>)
<%_ } _%>
<%_ } _%>

<%_ if (_hasQuery) { _%>
const showSearch = ref(true)
<%_ } _%>
const queryParams = ref({
  page: 1,
  limit: 10,
  <%_ for (const field of fieldList) { _%>
  <%_ if (field.query) { _%>
  <%= field.name %>: null,
  <%_ } _%>
  <%_ } _%>
})
<%_ if (_hasQuery) { _%>
/**
 * 搜索按钮操作
 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}
/**
 * 重置搜索按钮操作
 */
function resetQuery() {
  proxy.resetForm('queryFormRef')
  handleQuery()
}
<%_ } _%>

const loading = ref(false)
const tableData = ref([])
const total = ref(0)
/**
 * 获取 <%= comment %> 列表数据
 */
function getList() {
  loading.value = true
  const _queryParams = cloneDeep(queryParams.value)
  list<%= fn.snakeFormatHump(name, true) %>(_queryParams)
    .then((res) => {
      tableData.value = res.data.rows
      total.value = res.data.total
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}
<%_ if (hasDel || hasExport) { _%>

const selectTableData = ref([])
const multiple = ref(true)
/**
 * 表格前多选框选中数据
 */
function handleSelectionChange(selection) {
  selectTableData.value = selection
  multiple.value = !selection.length
}
<%_ } _%>
<%_ if(hasAdd) { _%>

/**
 * 添加按钮操作
 */
function handleAdd() {
  proxy.$refs['addOrEditRef'].handleAdd()
}
<%_ } _%>
<%_ if(hasEdit) { _%>

/**
 * 编辑按钮操作
 */
function handleEdit(row) {
  const _row = cloneDeep(row)
  proxy.$refs['addOrEditRef'].handleEdit(_row)
}
<%_ } _%>
<%_ if (hasDel) { _%>

/**
 * 删除按钮操作
 */
function handleDelete(row) {
  const _ids = row.<%= pkField.name %> || selectTableData.value.map((item) => item.<%= pkField.name %>)
  proxy.$modal
    .confirm('确认删除<%= pkField.label %>为' + _ids + '的数据项？')
    .then(function () {
      return del<%= fn.snakeFormatHump(name, true) %>({ ids: _ids })
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
<%_ } _%>
<%_ if (hasExport) { _%>

const btnExportLoading = ref(false)
<%_ if (_hasDict) { _%>
// 导出功能 字典数据整理
const dictKeyValue = {}
watch([<%- dictsDot %>], ([<%- dictsDot %>]) => {
  <%_ for (const field of fieldList) { _%>
  <%_ if (field.list) { _%>
  <%_ if (field.dict) { _%>
  dictKeyValue['<%= field.name %>'] = labelValueToKeyValue(<%= field.dict %>)
  <%_ } _%>
  <%_ } _%>
  <%_ } _%>
})
<%_ } _%>
/**
 * 导出按钮操作
 */
function handleExport() {
  btnExportLoading.value = true
  <%_
  // 导出 表头&数据 处理
  let headerText = ""
  let fieldText = ""
  for (let i in fieldList) {
    const fieldName = fieldList[i].name
    if (fieldList[i].list) {
      // 加单位
      let label = fieldList[i].label
      const unit = fieldList[i].unit
      if (unit != "") {
        label = label + "（" + unit + "）";
      }
      if (i != fieldList.length - 1){
        headerText += "'" + label + "', ";
        fieldText += "'" + fieldName + "', ";
      } else {
        headerText += "'" + label + "'";
        fieldText += "'" + fieldName + "'";
      }
    }
  }
  _%>
  const filename = '<%= comment %>'
  const header = [<%- headerText %>]
  const fields = [<%- fieldText %>]
  if (selectTableData.value.length) {
    proxy.$modal
      .confirm('是否导出选中数据')
      .then(() => {
        const data = exportFormatJson(fields, selectTableData.value<% if(_hasDict) { %>, dictKeyValue<% } %>)
        exportJsonToExcel({ header, data, filename })
        proxy.$modal.msgSuccess('导出成功')
        btnExportLoading.value = false
      })
      .catch(() => {
        btnExportLoading.value = false
      })
  } else {
    proxy.$modal
      .confirm('是否导出全部数据')
      .then(() => {
        export<%= fn.snakeFormatHump(name, true) %>(queryParams.value)
          .then((res) => {
            const data = exportFormatJson(fields, res.data<% if(_hasDict) { %>, dictKeyValue<% } %>)
            exportJsonToExcel({ header, data, filename })
            proxy.$modal.msgSuccess('导出成功')
            btnExportLoading.value = false
          })
          .catch(() => {
            btnExportLoading.value = false
          })
      })
      .catch(() => {
        btnExportLoading.value = false
      })
  }
}
/**
 * 导出按钮操作 后端生成前端请求下载（预留）
 */
/*
function handleExport() {
  proxy.download('<%= exportApi %>', {
    ...queryParams.value
  }, `<%= comment %>.xlsx`)
}
*/
<%_ } _%>

getList()
</script>

<style lang="scss" scoped></style>
